package com.example.forum.interceptor;

import com.example.forum.entity.Token;
import com.example.forum.entity.User;
import com.example.forum.mapper.TokenMapper;
import com.example.forum.mapper.UserMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//添加组件token拦截器
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Resource
    TokenMapper tokenMapper;
    @Resource
    UserMapper userMapper;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object hander)throws Exception{
        String token=request.getParameter("token");
        System.out.println(token);
        //去token表查userId iftoken==null
        //
        System.out.println(1234);
        if(token==null){
            System.out.println(12345);;
            throw new RuntimeException("1token无效，这是我抛出的运行异常");
        }
        //根据token查userID，根据userId查username
        Integer userId =tokenMapper.UidSelect(token);
        if(userId==null){
            throw new RuntimeException("token过期，根据token查不到userID");
        }
        String username= userMapper.username(userId);
        if (username==null){
            throw  new RuntimeException("未知错误，根据userid查不到username");
        }
        User user=User.builder().id(userId).username(username).build();
        //为什么此处不用新建类，直接就可以调用；
        UserContext.setUser(user);
        Token token1=Token.builder().token(token).build();
        TokenContext.setToken(token1);

        return true;
    }
}
